package com.zjw.nanyinge.feign.config.decoder;

import com.zjw.nanyinge.vo.resp.VoiceVO;
import feign.FeignException;
import feign.Response;
import feign.codec.DecodeException;
import feign.codec.Decoder;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.Map;

public class BaiduVoiceDecoder implements Decoder {
    @Override
    public Object decode(Response response, Type type) throws IOException, DecodeException, FeignException {
        Map<String, Collection<String>> headers = response.headers();
        String contentType = headers.get("Content-Type").stream().toList().get(0);
        if (!contentType.startsWith("audio")) {
            throw new DecodeException(response.status(), "百度服务器语音合成失败！", response.request());
        }
        Response.Body body = response.body();
        BufferedInputStream bis = new BufferedInputStream(body.asInputStream());
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int len = -1;
        while ((len = bis.read(buf)) != -1) {
            baos.write(buf, 0, len);
        }
        VoiceVO voiceVO = new VoiceVO();
        voiceVO.setFormat(contentType);
        voiceVO.setData(baos.toByteArray());
        return voiceVO;
    }
}
